import 'dart:developer';
import 'dart:io';

import 'package:core/extension/extension_date_time.dart';
import 'package:core/helper/global_helper.dart';
import 'package:flutter/cupertino.dart';

class LogHelper {

  const LogHelper._();

  static const _separator = '-';
  static const _split = '$_separator$_separator$_separator$_separator$_separator$_separator$_separator$_separator$_separator';
  static var _title = '';
  static var _isDebug = GlobalHelper.isDebug;
  static int _limitLength = 800;
  static String _startLine = '$_split$_title$_split>start';
  static String _endLine = '$_split$_title$_split>end';

  static void init({String title = '', required bool isDebug, int limitLength = 800}) {
    _title = title;
    _isDebug = isDebug;
    _limitLength = limitLength ??= _limitLength;
    _startLine = '$_split$_title$_split';
    var endLineStr = StringBuffer();
    var cnCharReg = RegExp('[\u4e00-\u9fa5]');
    for (int i = 0; i < _startLine.length; i++) {
      if (cnCharReg.stringMatch(_startLine[i]) != null) {
        endLineStr.write(_separator);
      }
      endLineStr.write(_separator);
    }
    _endLine = endLineStr.toString();
  }

  //仅Debug模式可见
  static void d(dynamic obj, {String? title}) {
    if (_isDebug) {
      _log(obj.toString(), title);
    }
  }

  static void v(dynamic obj, {String? title}) {
    _log(obj.toString(), title);
  }

  static void _log(String msg, String? title) {
    var time = DateTime.now().toHms;
    debugPrint('${title ?? ''}$_startLine-$time');

    if (msg.length < _limitLength) {
      debugPrint(msg);
    } else {
      segmentationLog(msg);
    }
    debugPrint('${title ?? ''}$_endLine-$time');
  }

  static void segmentationLog(String msg) {
    var outStr = StringBuffer();
    for (var index = 0; index < msg.length; index++) {
      outStr.write(msg[index]);
      if (index % _limitLength == 0 && index != 0) {
        debugPrint(outStr.toString());
        outStr.clear();
        var lastIndex = index + 1;
        if (msg.length - lastIndex < _limitLength) {
          var remainderStr = msg.substring(lastIndex, msg.length);
          debugPrint(remainderStr);
          break;
        }
      }
    }
  }

  static void _logEmptyLine() {
    debugPrint('');
  }
}
